__author__ = 'insect'

import tornado.web
import tornado.httpserver
import tornado.ioloop
import os

import pymongo
import web.config

mongo_connection = pymongo.Connection(web.config.MongoHOST, web.config.MongoPORT)
db=mongo_connection.example
jwc_test = db.secondtest

from tornado.options import define, options
define("port",default=9980,help="run on the given port",type=int)

class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r'/', IndexHandler),
            (r'/query/(.*)', SearchHandler),
        ]
        settings=dict(
            template_path=os.path.join(os.path.dirname(__file__), "templates"),
            static_path=os.path.join(os.path.dirname(__file__), "static")
        )
        tornado.web.Application.__init__(self, handlers, **settings)

class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("main.html")

class SearchHandler(tornado.web.RequestHandler):
    def get(self, form_name):
        form_name = unicode(form_name).encode('utf-8')
        search_result = jwc_test.find({"title":{'$regex': form_name}})
        new_search_result = []
        repetition_list = []
        for item in search_result:
            if item['url'] not in repetition_list:
                new_search_result.append(item)
                repetition_list.append(item['url'])
            else:
                continue
        print new_search_result
        self.render("search_list.html", result=new_search_result)

def main():
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

if __name__ == "__main__":
    main()

